/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.device;

import com.cxhd.lis.util.Tool;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author 52461
 */
public class Mejer_7001 {

    private String baseData;
    private String device_code = "us-2000";
    private String code = "LN";
    private String sampletype = "mejer-7001";
    private String sampletypeId = null;
    private String baseLine = System.getProperty("line.separator");

    public Mejer_7001(String baseData) {
        this.baseData = baseData;
        // getSampleTypeId();
        parseComData();

    }
  
    public void parseComData() {
        try {
            String sampleNo = null;
            String testDate = null;
            
        String testTime = null;
             Map<String, String> resultMap = new HashMap<String, String>();

          String alls[] = baseData.split(baseLine);

        for (int i = 0; i < alls.length; i++) {
            // System.out.println(i+":"+alls[i]);
            //第一行不做处理
            //第2行为 样本号和日期
            if (i == 1) {
                sampleNo = alls[i].split(" ")[0];//获取
                testDate = alls[i].split(" ")[5];
                System.out.println(alls[i].split(" ").length);

            } //第三行为时间
            else if (i == 2) {
                testTime = alls[i].trim();
            } //第三行之后为结果
            else if (i > 3) {
                parseResult(alls[i], resultMap);
            }
        }
            sendDb(Tool.getSampleNo(code, sampleNo), testDate, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据不完整解析错误");
        }
    }
    
     public void parseResult(String data, Map<String, String> map) {

        String das[] = data.trim().split(" ");

        if (das.length > 0 && das[0].trim().length() > 0) {
            String result = "";
            for (int n = 0; n < das.length; n++) {
                if (n > 0 && das[n].length() > 0) {
                    result += "   " + das[n];
                }
            }
            map.put(das[0], getResult(result));

        }
    }
 public String getResult(String result){
    
     return result.replace("mmol/L", "").replace("g/L", "").replace("umol/L", "").replace("Cells/uL", "");
    
    }
    public void sendDb(String sampleNo, String datetime, Map<String, String> result) {

        System.out.println(sampleNo + "  " + datetime);
         System.out.println(result);

        for (String key : result.keySet()) {
            try {
                System.out.println("保存到数据库");
                makeInsertSqlInsert(tranMap(sampleNo, datetime, key, result.get(key)), "lis_testresult");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    //转换数据结构
    public Map<String, String> tranMap(String sampleNo, String datetime, String key, String value) {
        try {
            Map<String, String> newMap = new HashMap<String, String>();
            //System.out.println("select * from lis_testdescribe where TESTID='" + key.trim().replace("*", "") + "' and SAMPLETYPE= '"+sampletypeId+"'");
            Record rs = Db.findFirst("select * from lis_testdescribe where TESTID='" + key.trim().replace("*", "") + "'");
            if (rs != null) {
                newMap.put("ITEMPK", rs.get("PK") + "");
                newMap.put("TESTID", rs.get("TESTID") + "");
                newMap.put("UNIT", rs.get("UNIT") + "");
                newMap.put("SAMPLENO", sampleNo);
                System.out.println(rs.getStr("TESTID"));
                if (rs.getStr("TESTID").equalsIgnoreCase("image#WBC") || rs.getStr("TESTID").equalsIgnoreCase("image#RBC") || rs.getStr("TESTID").equalsIgnoreCase("image#PLT")) {
                    newMap.put("RESULTFLAG", "1");
                    // System.out.println("yyyyyyyyyy-----------------------");
                } else {
                    newMap.put("RESULTFLAG", "0");
                }
                newMap.put("TESTRESULT", value);
                newMap.put("MEASURETIME", datetime);
                newMap.put("DEVICEID", device_code);
                newMap.put("SAMPLETYPE", "16");
                newMap.put("UUID", Tool.string2MD5(datetime.trim() + sampleNo.trim() + device_code));
                return newMap;

            }
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //构建sql
    private boolean makeInsertSqlInsert(Map<String, String> map, String tableName) throws Exception {

        if (map == null) {
            return false;
        }

        String sql = "";
        StringBuilder sqlHead = new StringBuilder();
        StringBuilder sqlvalue = new StringBuilder();
        int index = 0;
        String[] values = new String[map.size()];
        sqlHead.append("insert into ").append(tableName).append(" (");
        sqlvalue.append(" values (");
        for (String key : map.keySet()) {
            values[index] = map.get(key);
            index++;
            if (index == map.size()) {
                sqlHead.append("`").append(key).append("`").append(" )");
                sqlvalue.append(map.get(key) == null ? "null)" : "'" + map.get(key) + "')");
                // map.get(key)==null?"":"";
                // sqlvalue.append("? )");
            } else {
                sqlHead.append("`").append(key).append("`").append(" , ");
                sqlvalue.append(map.get(key) == null ? "null," : "'" + map.get(key) + "',");
                //sqlvalue.append("?,");
            }

        }
        sql = sqlHead.append(sqlvalue).toString();
        //System.out.println(sqlHead.append(sqlvalue).toString()+"  "+values.length);
        //logger.info(sql);
        try {
            Db.update(sql);
        } catch (Exception e) {
            System.out.println(e);
        }
        return true;

    }

}
